<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        width: 500px;
        height: 700px;
        display: block;
      }
    </style>
  </head>

  <body>
    <img class="lazyload" data-src="https://picsum.photos/id/100/500/700" />
    <img class="lazyload" data-src="https://picsum.photos/id/200/500/700" />
    <img class="lazyload" data-src="https://picsum.photos/id/210/500/700" />
  </body>

  <script>
    // 判断元素是否在视口内
    function isInViewport(element) {
      // 获取视口高度和宽度
      const { innerHeight, innerWidth } = window

      const rect = element.getBoundingClientRect()

      // 以下是两种判断，可自行选择
      return rect.top >= 0 && rect.top < innerHeight && rect.left < innerWidth // 只考虑上下滚动时，出现在视口的情况
      // return rect.top >= 0 && rect.left >= 0 && rect.bottom <= innerHeight && rect.right <= innerWidth // 完全进入视口
    }

    function setLazyLoad() {
      // 获取需要懒加载的图片元素
      const lazyloadImages = document.querySelectorAll(".lazyload")

      lazyloadImages.forEach(img => {
        if (isInViewport(img)) {
          img.src = img.dataset.src
          img.classList.remove("lazyload")
        }
      })
    }

    setLazyLoad()

    // 监听窗口的滚动事件
    window.addEventListener("scroll", setLazyLoad)
  </script>
</html>
